package per.destiny.seckill.service;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import per.destiny.seckill.mapper.SeckillOrderMapper;
import per.destiny.seckill.pojo.SeckillOrder;
import per.destiny.seckill.pojo.SeckillOrderExample;

import java.util.List;

@Service
public class SeckillOrderService {

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public SeckillOrder getOne(Long userId, Long goodsId) {
        SeckillOrderExample seckillOrderExample = new SeckillOrderExample();
        seckillOrderExample.createCriteria().andUserIdEqualTo(userId).andGoodsIdEqualTo(goodsId);
        List<SeckillOrder> seckillOrders = seckillOrderMapper.selectByExample(seckillOrderExample);
        if (CollectionUtils.isEmpty(seckillOrders)) {
            return null;
        }
        return seckillOrders.get(0);
    }

    public Long getResult(Long userId, Long goodsId) {
        SeckillOrder seckillOrder = getOne(userId, goodsId);
        if (seckillOrder != null) {
            return seckillOrder.getOrderId();
        } else if (redisTemplate.hasKey("isDBStockEmpty:" + goodsId)) {
            // 通过Redis判断数据库的库存。
            return -1L;
        } else {
            return 0L;
        }
    }
}
